package demo.jvm;


import tech.medivh.classpy.classfile.ClassFile;
import tech.medivh.classpy.classfile.ClassFileParser;

import java.io.File;
import java.nio.file.Files;
import java.util.List;

/**
 * @author : feixiang.li
 * @since : 2025-09-22 11:30
 */
public class BootstrapClassLoader {

    private List<String> classPath;

    public BootstrapClassLoader(List<String> classPath) {
        System.out.println("启动类加载器");
        System.out.println(classPath);
        this.classPath = classPath;
    }


    public ClassFile loadClass(String fqcn) throws ClassNotFoundException {
        ClassFile mainClassFile =
                classPath.stream()
                        .map(path -> tryLoad(path, fqcn))
                        .filter(classFile -> classFile != null)
                        .findFirst()
                        .orElse(null);
        return mainClassFile;
    }

    public ClassFile tryLoad(String path, String mainClass) {
        File classFilePath = new File(path, mainClass.replace(".", File.separator) + ".class");
        System.out.println(classFilePath);
        if (!classFilePath.exists()) {
            System.out.println("类文件不存在");
            return null;
        }

        try {
            byte[] bytes = Files.readAllBytes(classFilePath.toPath());
            return new ClassFileParser().parse(bytes);
        } catch (Exception e) {
            return null;
        }

    }
}
